import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react-swc'
import path from 'path'
import { readFileSync } from 'node:fs'
import typescript from '@rollup/plugin-typescript'
const resolve = (dir: string) => path.resolve(__dirname, dir)
/**
 *  读取文件
 */
const packageJson = JSON.parse(
  readFileSync('./package.json', { encoding: 'utf-8' })
)
/**
 *  全局变量
 */
const globals = {
  ...(packageJson?.dependencies || {})
}
// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    react(),
    typescript({
      target: 'es5',
      rootDir: resolve('src/'),
      declaration: true,
      declarationDir: resolve('lib'),
      exclude: resolve('node_modules/**'),
      allowSyntheticDefaultImports: true
    }),
  ],
  css: {
    preprocessorOptions: {
      less: {
        additionalData: `@import "${resolve('src/styles/variables.less')}";`,
        javascriptEnabled: true,
      },
    },
  },
  build: {
    outDir:'lib',
    lib:{
      entry: resolve('src/wms-index.tsx'),
      name: 'wms',
      fileName: (format) => `wms.${format}.js`,
      // 打包格式
      formats: ['es', 'cjs']
    },
    rollupOptions: {
      // input:{
      //   wms: resolve('wxzd/wms/index.html')
      // },
      // output: {
      //   manualChunks(id){
      //     if (id.includes('node_modules')) {
      //       return 'vendor'
      //     }
      //   },
      //   entryFileNames:(chunkInfo) =>{
      //     // console.log('entry',chunkInfo)
      //     return 'wxzd/[name]/js/[name].[hash].js'
      //   },
      //   chunkFileNames:(chunkInfo) =>{
      //     // console.log('chunk',chunkInfo)
      //     if(chunkInfo.name.includes("platform")){
      //       return '[name]/chunk/[name].[hash].js'
      //     }
      //     if(chunkInfo.name.includes("wms")){
      //       return '[name]/chunk/[name].[hash].js'
      //     }
      //     return 'chunk/[name].[hash].js'
      //   },
      //   assetFileNames:(chunkInfo)=>{
      //     // console.log('asset',chunkInfo)
      //     if(chunkInfo.name.includes("wms")) {
      //       return 'wxzd/[name]/[ext]/[name].[hash].[ext]'
      //     }
      //     return '[ext]/[name].[hash].[ext]'
      //   }
      // },
      external: ['react',
        'react-dom',
        'antd',
        '*.svg',
        'react/jsx-runtime',
        ...Object.keys(globals)],
    },

  },
  server:{
    port: 5000,
    host: '0.0.0.0',
    open: false,
    cors: true,
    proxy:{
      '/api':{
        target:"http://192.168.22.140:8999",
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, '')
      }
    }
  }
})
